<?php defined('SYSPATH') or die('No direct script access.');

require_once APPPATH . '/vendor/loghtopenid/openid.php';

class OpenId_Controller extends PublicController {

	private $discoveryUrls;
	private $discoveryUrlYahoo = 'https://me.yahoo.com';
	
	
	public function __construct() {
		parent::__construct();
		$this->discoveryUrls = array(
				'google' => 'https://www.google.com/accounts/o8/id',
				'yahoo' => 'https://me.yahoo.com');
		// Seznam.cz uses dynamic URLs
		// http://napoveda.seznam.cz/cz/login/openid/jak-vypada-openid-od-seznam-cz/
	}

	public function index() {
		$this->renderSubview('openIdForm');
	}
	
	public function process() {
		
		try {
			$openid = new LightOpenID(Kohana::config('yosemin.openIdHost'));
			if(!$openid->mode) {
				$this->sendAuthRequest($openid);
		    }
		    else if ($openid->mode == 'cancel') {
		    	$this->cancelled();
		        echo 'User has canceled authentication!';
		    }
		    else {
		    	if ($openid->validate()) {
		    		$this->success($openid->identity);
		    	}
		    	else {
		    		$this->failure();
		    	}
		    }
		}
		catch(ErrorException $e) {
		    echo $e->getMessage();
		}
	}
	
	private function sendAuthRequest($openid) {
		$openid->identity = $this->discoveryUrls['google'];
		// $openid->returnUrl = 'https://' . $_SERVER['SERVER_NAME'] . url::site('/openId/process');
		$openid->required = array('contact/email');
		header('Location: ' . $openid->authUrl());
		exit();
	}
	
	private function cancelled() {
		echo 'User cancelled the authentication.';
	}
	
	private function success($identity) {
		echo 'User ' . $identity . ' has logged in.';
		print_r($openid->getAttributes());
	}
	
	private function failure($identity) {
		echo 'Login failure.';
	}
}
